/*
* WuManber.cpp - This file is the part of the StringSearch.
* Copyright (C) 2010 Dean Lee <deanlee3@gmail.com> <http://www.deanlee.cn/>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program.  If not, see <http://www.gnu.org/licenses/>.
* 
* Acknowledgements:
*   <> Many thanks to all of you, who have encouraged me to update my articles
*     and code, and who sent in bug reports and fixes.
* 
*/

#include "stdafx.h"
#include "WuManber.h"


// CWuManber
STDMETHODIMP CWuManber::AddPatterns(BSTR patterns, BSTR separator, VARIANT_BOOL caseSensitive)
{
	if (m_handle)
	{
		CComBSTR p(patterns);
		LPTSTR next = NULL;
		LPCTSTR token = _tcstok_s(p, separator, &next);
		while (token != NULL)
		{
			mwmAddPatternEx(m_handle, (BYTE*)token, _tcslen(token) * sizeof(TCHAR), !caseSensitive, 0, 0, m_handle, 0);
			token = _tcstok_s( NULL, separator, &next);
		}
		mwmPrepPatterns(m_handle);

	}
	return S_OK;
}

int Match( void * id, int index, void * data )
{
	CWuManber* self = (CWuManber*)data;
	self->setIndex(index);
	return 1;
}

STDMETHODIMP CWuManber::Search(BSTR string, LONG* pIndex)
{
	if (m_handle)
	{
		m_index = -1;
		int nFound = mwmSearch(m_handle, (unsigned char*)string, _tcslen(string) * sizeof(WCHAR), Match, this);
		if (pIndex)
		{
			*pIndex = m_index / 2;
		}
	}
	return S_OK;
}

void CWuManber::setIndex(int index)
{
	m_index = index;
}
